<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">

      <el-form-item label="昵称" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入昵称"
          clearable
          size="small"
          maxlength="11"
          @input="handleQuery"
        />
      </el-form-item>
      <el-form-item label="微信手机号" prop="telephone">
        <el-input
          v-model="queryParams.telephone"
          placeholder="请输入微信手机号"
          clearable
          size="small"
          maxlength="11"
          @input="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="余额" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入余额"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="是否停运标志，0代表正常，1代表停运，默认为0" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择是否停运标志，0代表正常，1代表停运，默认为0" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['system:recharge:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:user:edit']"
        >修改</el-button>
      </el-col> -->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['system:recharge:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="info"-->
<!--          icon="el-icon-upload"-->
<!--          size="mini"-->
<!--          @click="handleImport"-->
<!--          v-hasPermi="['system:recharge:import']"-->
<!--        >导入</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:recharge:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
       <el-table-column fixed label="序号" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum-1)*queryParams.pageSize+(scope.$index + 1)}} </span>
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center" prop="username" />
      <el-table-column label="微信手机号" align="center" prop="telephone" />
      <el-table-column label="余额 (元)" align="center" prop="balanceFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="recharge(scope.row)"
            v-hasPermi="['system:recharge:edit']"
          >充值</el-button>



          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rulesTwo" label-width="95px">
        <el-form-item label="手机号" prop="username">
          <el-input v-model="form.username" placeholder="请输入手机号" maxlength="20" minlength="2" />
        </el-form-item>
        <el-form-item label="微信手机号" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输入微信手机号" maxlength="20" minlength="2" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 充值对话框 -->
    <el-dialog :title="title" :visible.sync="open2" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="85px">

        <el-form-item label="手机号" prop="username">
          <el-input v-model="form.username" placeholder="请输入手机号" disabled />
        </el-form-item>
        <el-form-item label="微信手机号" prop="wxtel">
          <el-input v-model="form.telephone" placeholder="请输入微信手机号" disabled />
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input v-model="form.balance" placeholder="请输入余额" disabled />
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入充值金额" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :action="upload.url"
        :headers="upload.headers"
        :before-upload="beforeFileUpload"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件, 最大不超过10M！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, exportUser } from "@/api/Recharge/user";
import { getToken } from '@/utils/auth';

export default {
  name: "User",
  data() {
    return {
      upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          headers: { Authorization: "Bearer " + getToken() },
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/app/user/import"
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        role: undefined,
        card: undefined,
        name: undefined,
        username: undefined,
        password: undefined,
        address: undefined,
        department: undefined,
        telephone: undefined,
        amount: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // username: [
        //   { required: true, message: "手机号不能为空", trigger: "blur" }
        // ],
        balance: [
          { required: true, message: "余额不能为空", trigger: "blur" }
        ],
        amount: [
            { required: true, message: "充值金额不能为空", trigger: "blur" },
            // { type: 'number', message: '充值金额必须为数字'}
        ],
      },
      rulesTwo: {
          telephone: [
              { required: true, message: "微信手机号不能为空", trigger: "blur" }
          ],
          username: [
              { required: true, message: "手机号不能为空", trigger: "blur" }
          ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 充值取消按钮
    cancel2() {
      this.open2 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        role: undefined,
        card: undefined,
        name: undefined,
        username: undefined,
        password: undefined,
        address: undefined,
        department: undefined,
        telephone: undefined,
        amount: undefined,
        status: "0",
        createTime: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 充值按钮操作 */
    recharge(row) {
      this.reset();
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data;
        this.open2 = true;
        this.title = "充值";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
        if(this.form.amount<=0){
            this.msgError("请输入大于0的数字");
            return false
        }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateUser(this.form).then(response => {
                console.log(response)
              if (response.code == 0) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addUser(this.form).then(response => {
              if (response.code == 0) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 充值提交按钮 */
    submitForm2: function() {
        if(this.form.amount<=0){
            this.msgError("请输入大于0的数字");
            return false
        }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateUser(this.form).then(response => {
                console.log(response)
              if (response.code == 0) {
                this.msgSuccess("充值成功");
                this.open2 = false;
                this.getList();
              }
            });
          } else {
            addUser(this.form).then(response => {
              if (response.code == 0) {
                this.msgSuccess("新增成功");
                this.open2 = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除用户编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUser(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户数据?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportUser(queryParams);
        }).then(response => {
          this.download(response.data);
        }).catch(function() {});
    },
     /** 导入按钮操作 */
    handleImport() {
        this.upload.title = "用户导入";
        this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
        importTemplate().then(response => {
            this.download(response.data);
        });
    },
    // 文件上传前处理
    beforeFileUpload (file) {
      console.log("file.type========:" + file.type);
      // const fileType = file.type === 'image/xls' || file.type === 'image/xlsx'
      const isLt10M = file.size / 1024 / 1024 < 10;
      // if (!fileType) {
      //   this.$message.error("上传文件只能是 xls和xlsx 格式!");
      //   return false;
      // }
      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过 10M!");
        return false;
      }
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.message, "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
    },
    // 提交上传文件
    submitFileForm() {
        this.$refs.upload.submit();
    }
  }
};
</script>
